/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root)
    {
        if (root == nullptr) return;

        stack<TreeNode*> st;
        TreeNode* cur = root;
        while (true)
        {
            if (cur->right != nullptr)st.push(cur->right);

            if (cur->left != nullptr)
            {
                cur->right = cur->left;
                cur->left = nullptr;
            }
            else
            {
                if (st.empty() == true) break;
                else cur->right = st.top(), st.pop();
            }
            cur = cur->right;
        }
    }
};